package smedi.ismedi.web.bff.infrastructure.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * @Author Jimmy
 * @Date 2021/6/29 10:52
 */
@Slf4j
public class FileHelper {
    public static String getUrl(String url, String group, String path, String fileName, HttpServletResponse response) {
        return url + group + "/" + path;
    }

    public static void downloadFile(String url, String group, String path, String fileName, HttpServletResponse response) {
        String filePath = String.format("%s/%s/%s", url, group, path);
        byte[] b = fileToBytes(filePath);
        try {
            response.reset();
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
            response.getOutputStream().write(b);
            response.getOutputStream().close();
        } catch (IOException e) {
            log.debug("下载文件输出流异常：{}", e);
        }
    }


    public static byte[] fileToBytes(String filePath) {

        try {
            URL url = new URL(filePath);
            URLConnection connection = url.openConnection();
            InputStream is = connection.getInputStream();

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = is.read(buffer))) {
                output.write(buffer, 0, n);
            }
            return output.toByteArray();
        } catch (Exception ex) {
        }
        return null;

    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}
